/*
 * time.windows.com
 * time.nist.gov
 * s1a.time.edu.cn
 * s1c.time.edu.cn
 * time-nw.nist.gov
 * time-a.nist.gov
 * time-b.nist.gov
 * s1b.time.edu.cn
 * nist1.aol-ca.truetime.com
 *
 * https://blog.csdn.net/dosthing/article/details/81588219
 */

package addition.ntp;

import org.apache.commons.net.ntp.*;

import java.io.IOException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * 用 NTP 协议，编写或下载读取网络时间的程序，运行后要能获取到正确的网络时间。
 * 提示：使用 Apache Commons Net 库中的 NtpV3Packet 接口和实现类。
 */
public class NtpDemo {

    public static void main(String[] args) throws IOException {
        NTPUDPClient timeClient = new NTPUDPClient();
        String timeServerUrl = "time-a.nist.gov";
        InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);
        TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
        TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(dateFormat.format(timeStamp.getDate()));
    }

}
